<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="品牌名称" prop="brand_name">
        <el-input v-model="queryParams.brand_name" placeholder="品牌名称" clearable size="small" />
      </el-form-item>
      <el-form-item label="商品spu" prop="goods_spu">
        <el-input v-model="queryParams.goods_spu" placeholder="商品spu" clearable size="small" />
      </el-form-item>
      <el-form-item label="商品名称" prop="goods_name">
        <el-input v-model="queryParams.goods_name" placeholder="商品名称" clearable size="small" />
      </el-form-item>
      <el-form-item label="商品分类">
        <el-cascader
          v-model="category_ids"
          placeholder="请选择"
          :options="options1"
          :props="props"
          collapse-tags
          clearable
        />
      </el-form-item>
      <el-form-item label="贸易类型">
        <el-select v-model="queryParams.trade_type_name" clearable placeholder="请选择">
          <el-option v-for="item in options2" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否上架">
        <el-select v-model="queryParams.is_sale" clearable placeholder="请选择是否上架">
          <el-option v-for="item in isSaleOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="筛选">
        <el-select v-model="queryParams.supplier_id" clearable placeholder="请选择">
          <el-option v-for="item in [0,1,2,3]" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-action="'goods@create'" type="primary" icon="el-icon-plus" size="mini" @click="openAdd('a', '添加')">添加
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-action="'goods@sync'" type="primary" size="mini" @click="openCreate()">候鸟同步
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-tooltip :disabled="selectGoodsSpu != ''" class="item" effect="dark" content="请先选中一个商品" placement="top-start">
          <el-button type="danger" :disabled="selectGoodsSpu == ''" plain size="mini" @click="openMenuDialog">更多操作</el-button>
        </el-tooltip>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" size="mini" @click="openDisableCategory">禁用分类</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" size="mini" @click="openOrderTemplate">清单表体模板</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" highlight-current-row :data="list" style="width: 100%;" @current-change="handleCurrentChange" @selection-change="handleSelectionChange">
      <!--      <el-table-column type="selection" align="center" width="50" label="iddd" />-->
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="SPU" align="center" prop="goods_spu" />
      <el-table-column label="品牌名" align="center" prop="brand_name" />
      <el-table-column label="商品名称" align="center" prop="goods_name" />
      <el-table-column label="贸易类型" align="center" prop="trade_type_name" />
      <el-table-column label="销售价格" align="center" prop="price" />
      <el-table-column v-if="ifAdmin" label="成本价格" align="center" prop="cost_price" />
      <el-table-column label="库存" align="center" prop="stock" />
      <el-table-column label="商品图片" align="center">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.goods_pic"
            :src="scope.row.goods_pic"
            style="height: 50px"
            :preview-src-list="scope.row.goods_pic.split(',')"
          />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="is_sale" :formatter="isSaleFormatter">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.is_sale === 1" size="mini">{{ isSaleFormatter(scope.row) }}</el-tag>
          <el-tag v-else-if="scope.row.is_sale === 0" size="mini" type="danger">{{ isSaleFormatter(scope.row) }}</el-tag>
          <span style="margin-left: 10px">{{ scope.row.date }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template v-slot="scope">
          <!-- :disabled="scope.row.id === 1" -->
          <el-button v-action="'goods@update'" size="mini" type="primary" @click="openAdd(scope.row, '编辑')">编辑</el-button>
          <el-button v-action="'goods@delete'" size="mini" type="danger" @click="delPort(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.limit"
      @pagination="getList"
    />
    <!-- 新增/修改 -->
    <Add :open.sync="open1" :title="title1" :form="form1" @getList="getList" @refresh="newList()" />
    <!-- 候鸟同步 -->
    <BirdAction :open.sync="open" :title="title" :form="form" @getList="getList" @refresh="newList()" />

    <!-- 通知菜单弹窗   -->
    <ActionDialog :visible.sync="menuDialogVisible" :spu="selectGoodsSpu" @close="handleMenuDialogClose" />

    <!-- 禁用分类抽屉 -->
    <DisableCategoryDrawer :visible.sync="disableCategoryVisible" @save="handleDisableCategorySave" />

    <!-- 订单表体模板弹窗 -->
    <OrderTemplateDialog :visible.sync="orderTemplateVisible" />

  </div>
</template>
<style>
.el-input__inner {
  width: 90%;
}

.el-input__suffix {
  right: 10%;
}
</style>
<script>
import { getList, delGoods, getCategory } from '@/api/externalGoods'
import { mapGetters } from 'vuex'
import Add from './Add'
import BirdAction from './BirdAction'
import ActionDialog from '@/views/externalGoods/goods/component/ActionDialog'
import DisableCategoryDrawer from '@/views/externalGoods/goods/component/DisableCategoryDrawer'
import OrderTemplateDialog from './component/OrderTemplateDialog'
export default {
  name: 'Index',
  components: {
    Add,
    BirdAction,
    ActionDialog,
    DisableCategoryDrawer,
    OrderTemplateDialog
  },
  data() {
    return {
      selectGoodsSpu: '',
      menuDialogVisible: false,
      // 遮罩层
      loading: true,
      open: false,
      title: '',
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      portConfig: [],
      info: '',
      // 查询参数
      queryParams: {
        page: 1,
        limit: 10,
        brand_name: undefined,
        is_sale: 1
      },
      options1: [],
      options2: [{
        value: '保税直供',
        label: '保税直供'
      }, {
        value: '完税进口',
        label: '完税进口'
      }, {
        value: '国内贸易',
        label: '国内贸易'
      }, {
        value: '香港直邮',
        label: '香港直邮'
      }, {
        value: '海外直邮',
        label: '海外直邮'
      }],
      isSaleOptions: [{
        value: 1,
        label: '上架'
      }, {
        value: 0,
        label: '下架'
      }],
      props: { checkStrictly: true, label: 'name', value: 'id' },
      category_ids: [],
      form: {},
      show: false,
      ids: [],
      multiple: false,
      rules: {
        brand_name: [
          { required: true, message: '请填写品牌名称', trigger: 'change' }
        ],
        manufacturer_id: [
          { required: true, message: '请选择制造商', trigger: 'change' }
        ]
      },
      dialogImageUrl: '',
      dialogVisible: false,
      importHeaders: { authorization: 'Bearer ' + this.token },
      fileList: [],
      url: undefined,
      open1: false,
      title1: '',
      form1: {},
      ifAdmin: false,
      disableCategoryVisible: false,
      orderTemplateVisible: false
    }
  },
  created() {
    this.importHeaders.authorization = 'Bearer ' + this.token
    this.url = process.env.VUE_APP_BASE_API + '/upload/image'
    this.getList()
    this.getCategoryList()
    const Array = this.$store.state.user.roles
    Array.forEach(item => {
      if (item === 'admin') {
        this.ifAdmin = true
      } else if (item === 'admin1') {
        this.ifAdmin = true
      } else {
        this.ifAdmin = false
      }
    })
  },
  computed: {
    ...mapGetters([
      'token'
    ])
  },
  methods: {
    handleCurrentChange(val) {
      this.selectGoodsSpu = val.goods_spu
    },
    openMenuDialog() {
      if (this.selectGoodsSpu == '') {
        return this.$message({
          message: '请选择商品',
          type: 'error'
        })
      }
      this.menuDialogVisible = true
    },
    handleMenuDialogClose() {
      this.menuDialogVisible = false
    },
    handleMenuAction(action) {
      this.$message(`执行了 ${action}`)
    },
    isSaleFormatter(row) {
      return row.is_sale == 1 ? '上架' : '下架'
    },
    // 获取列表
    getCategoryList() {
      getCategory().then(res => {
        if (res.code === 10000) {
          // console.log(res)
          this.options1 = res.data
        }
      })
    },
    newList() {
      this.getList()
    },
    delPort(row) {
      delGoods(row.id).then(res => {
        console.log(res)
        if (res.code === 10000) {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.getList()
        }
      })
    },
    openAdd(row, type) {
      if (type === '添加') {
        this.open1 = true
        this.title1 = '添加'
        this.form1 = {}
      } else {
        this.open1 = true
        this.title1 = '编辑'
        this.form1 = row
      }
    },
    openCreate() {
      this.open = true
      this.title = '候鸟同步'
      this.form = {}
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    /** 打开 */
    handleCreate(row, title) {
      const that = this

      if (that.$refs['form']) {
        that.$refs['form'].clearValidate()
      }
      if (that.$refs['upload']) {
        that.$refs['upload'].clearFiles()
      }
      that.fileList = []
      if (row.brand_image) {
        const list = row.brand_image.split(',')
        for (let i = 0; i < list.length; i++) {
          that.fileList.push({ url: list[i] })
        }
      }
      that.form = row
      that.title = title
      that.open = true
    },
    /** 查询清单列表 */
    getList() {
      this.loading = true
      this.selectGoodsSpu = ''
      if (this.category_ids) {
        this.category_ids.forEach(item => {
          this.queryParams.category_id = item
        })
      }
      getList(this.queryParams).then(response => {
        console.log(response)
        this.list = response.data
        this.total = response.count
        this.loading = false
      })
    },
    uploadSuccess(response, file, fileList) {
      if (response.code === 10000) {
        this.form.brand_image = response.data
      }
    },
    limit(file, fileList) {
      this.$message.warning('只需要上传一张')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        page: 1,
        limit: 10,
        brand_name: undefined
      }
      this.handleQuery()
    },
    /** 选中的项 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.multiple = !selection.length
    },
    openDisableCategory() {
      this.disableCategoryVisible = true
    },
    handleDisableCategorySave(categoryIds) {
      console.log('禁用的分类ID:', categoryIds)
      // TODO: 调用接口保存禁用分类
      this.$message.success('设置成功')
    },
    openOrderTemplate() {
      this.orderTemplateVisible = true
    }
  }
}
</script>

